#coding:utf8

def jwt_response_payload_handler(token, user, request):

    return {
        'token':token,
        'user_id':user.id,
        'username':user.username
    }

from users.models import User
import re
from django.contrib.auth.backends import ModelBackend
#第一种方式
def get_user_by_account(account):
    try:
        if re.match(r'1[345789]\d{9}', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        user = None
    return user

class UsernameMobileAuthBackend(ModelBackend):


    def authenticate(self, request, username=None, password=None,**kwargs):

        user = get_user_by_account(username)

        if user is not None and user.check_password(password):
            return user
        else:
            return None

#第二种方式

class SettingsBackend(object):

    def authenticate(self, request, username=None, password=None):

        user = get_user_by_account(username)
        if user is not None and user.check_password(password):
            return user

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None